package com.qf.shop.order.utils;

import com.qf.shop.common.constants.OrderConstatns;
import com.qf.shop.order.interceptor.LoginInterceptor;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

@Component
public class OrderUtils {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * yyyMMdd+用户ID后四位+4位随机数+流水号(唯一)
     * 生成订单ID
     *
     * @return
     */
    public String createOrderId(String uid) {

        StringBuffer buffer = new StringBuffer();

        // 时间
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());

        // 用户Id后四位()
        String lastUid = getLastUserId(uid);

        // 获取四位随机数
        String random = RandomStringUtils.random(4, false, true);

        // 流水号
        Long orderNum = stringRedisTemplate.opsForValue().increment(OrderConstatns.ORDER_ID_NUM);

        return buffer.append(date).append(lastUid).append(random).append(orderNum).toString();
    }

    // 获取用户Id后四位，如果不够四位补零
    public String getLastUserId(String uid) {
        if (uid.length() >= 4) {
            return uid.substring(uid.length() - 4);
        }

        for (int i = 0; i <= (4 - uid.length()); i++) {
            uid = "0" + uid;
        }
        return uid;
    }

    public static void main(String[] args) {
        String uid = "12";
        String uid2 = "1234";
        String uid3 = "123456789";
//        String lastUserId = getLastUserId(uid);
//        String lastUserId2 = getLastUserId(uid2);
//        String lastUserId3 = getLastUserId(uid3);
//        System.out.println(lastUserId);
//        System.out.println(lastUserId2);
//        System.out.println(lastUserId3);

        String oid = "202108310015603647";
    }

    public Integer getLastUserIdByOrderId(String orderId) {
        return Integer.parseInt(orderId.substring(8, 8 + 4));
    }
}
